const mongoose = require('mongoose')
// const config = require('config-lite')
const chalk = require('chalk')

const db = mongoose.connection
db.on('error', err => {
  chalk.red('MongoDb connection error')
})

db.once('open', () => {
  chalk.green('MongoDb connect successfully')
})

// mongoose.connect(config.url)
mongoose.connect("mongodb://localhost:27017/ele", {useNewUrlParser: true, useUnifiedTopology: true})



// 定义schema
const kittySchema = new mongoose.Schema({
  name: String
})

// 给schma添加行为
// kittySchema.methods.speak = function(){
//   const greeting = this.name
//     ? "My name is " + this.name
//     : "I don't have a name"
//   console.log(greeting)
// }

// 将schema交给model编译
// model是用来构造文档的类
const Kitten = mongoose.model('Kitten', kittySchema)

// 创建一个文档
const silence = new Kitten({name: 'cailunduo'})

// 保存数据到数据库
// silence.save((err, kittens) => {
//   if(err) return chalk.red(err)
//   console.log(kittens)
// })

// 查询所有kittens，通过Model的find
// Kitten.find((err, kittens) => {
//   if(err) return chalk.red(err)
//   console.log(kittens)
// })


// 按照name查询数据
// Kitten.find({name: /^cailunduo/}, (err, kittens) => {
//   if(err) return chalk.red(err)
//   console.log(kittens)
// })





